package com.zrb.mobile;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.Header;
 

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.mobile.adapter.Project_surveyprocessAdapter;
 
import com.zrb.mobile.adapter.model.ProjectSurveyDetailDto;
import com.zrb.mobile.adapter.model.ProjectSurveyDetailDtos;
import com.zrb.mobile.anim.Techniques;
import com.zrb.mobile.anim.YoYo;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.CustomloadingView;
import com.zrb.mobile.ui.LinearLayoutForListView;
import com.zrb.applib.utils.AppSetting;
 
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

import android.net.Uri;
import android.os.Bundle;
import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class User_my_surveyinfo extends BaseImgActivity implements OnClickListener  {

 
	LinearLayout layout_container,topcontent1,LinearLayout_top;
	LinearLayout relative_afk,relative_afk1,relative_afk2;
	Tip progTip;
	CustomloadingView mloadingView;
	int curPageindex=0;
 
	private double Lat=0,Lng=0;
	LinearLayoutForListView attachlistview;
	Project_surveyprocessAdapter msurveyProcessAdapter;
 
	int inspectId;
	Button cancelbtn;
	Dialog AuthDialog;
	TextView stepbg,stepProcess,stepfinish,topcontent,tv_location_area,cancel_reason;
	View linebg,linefinish;
	int curSurveyStatus=-1,projectId;
	ProjectSurveyDetailDto curSurveyDto;
	public static boolean hasNew=false;
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.u_center_mysurveyinfo);
		if (bundle != null)
			restoreSelf(bundle);
		else {
			inspectId=this.getIntent().getIntExtra("inspectId", -1);
		}
		
		 initView();
 		 LoadData();
  	}
	
	@Override
	protected void onResume() {
		if(hasNew){
			hasNew=false;
			Intent intent = new Intent(User_my_surveyinfo.this, User_my_surveyinfo.class); 
			startActivity(intent);
		}
		 
		super.onResume();
	}
	
	@Override
	protected  void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putInt("inspectId", inspectId);
        outState.putDouble("lon", Lng);
	    outState.putDouble("lat", Lat);
    }
	 
    private void restoreSelf(Bundle savedInstanceState)
    {
    	inspectId = savedInstanceState.getInt("inspectId",-1);
    	Lng = savedInstanceState.getDouble("lon");
    	Lat= savedInstanceState.getDouble("lat");
    }
     
	private void initView(){
 	
		View lefticon= this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
		TextView txtTitle=	(TextView)this.findViewById(R.id.txt_title);
		txtTitle.setText("��������");
		attachlistview=(LinearLayoutForListView)this.findViewById(R.id.attach_listview);
		cancelbtn=(Button)this.findViewById(R.id.logout_btn);
		cancelbtn.setOnClickListener(this);;
	 	//inspectStatus
		mloadingView=(CustomloadingView)this.findViewById(R.id.list_emptyview);
		mloadingView.SetOnRefleshListener(this);
		mloadingView.ShowLoading();
		
		stepbg=(TextView)this.findViewById(R.id.btn_step_start);
		stepProcess=(TextView)this.findViewById(R.id.btn_step_process);
		stepfinish=(TextView)this.findViewById(R.id.btn_step_finish);
		linebg=this.findViewById(R.id.line_step_start);
		linefinish=this.findViewById(R.id.line_step_finish);
	 	
		tv_location_area = (TextView) this.findViewById(R.id.tv_location_area);
		this.findViewById(R.id.tv_location_layout).setOnClickListener(this);
		
		LinearLayout_top = (LinearLayout) this.findViewById(R.id.linearLayout_top);
//		topcontent = (TextView) this.findViewById(R.id.topcontent);
		
	 	relative_afk = (LinearLayout) this.findViewById(R.id.relative_afk);
		relative_afk1 = (LinearLayout) this.findViewById(R.id.relative_afk1);
		relative_afk2 = (LinearLayout) this.findViewById(R.id.relative_afk2); 
		relative_afk.setOnClickListener(this);
		relative_afk1.setOnClickListener(this);
		relative_afk2.setOnClickListener(this);

		cancel_reason = (TextView) this.findViewById(R.id.cancel_reason);
 	}
   	
	/**����״̬��0��ȡ��1�����룻2��ȷ�ϣ�3�����**/
	private void showstep(int code){
		 curSurveyStatus=code;
 		if(code==Constants.InspectCancel) {
 			this.findViewById(R.id.cancel_layout).setVisibility(View.VISIBLE);
		/*	stepbg.setTextColor(Color.rgb(95, 95, 95));
 			stepProcess.setBackgroundResource(R.drawable.ring_whitebg);
 			stepProcess.setTextColor(Color.rgb(95, 95, 95));
			stepfinish.setBackgroundResource(R.drawable.ring_whitebg);
			stepfinish.setTextColor(Color.rgb(95, 95, 95));*/
			return;
		}
 		if(code>Constants.InspectCancel) stepbg.setEnabled(true);
		if(code>Constants.InspectApply){ 
			  stepProcess.setEnabled(true);
		       linebg.setSelected(true);
		}
		if(code>Constants.InspectConfirm){ 
			   stepfinish.setEnabled(true);
		      linefinish.setSelected(true);
		}
 	}
	
	private void LoadData()
	{
		//http://172.17.2.13:8090/inspect/queryUserInspectDetail?inspectId=4&zrb_front_ut=9198112ff75b700e2d419a9c407b2202
     	String url=String.format("inspect/queryUserInspectDetail?inspectId=%1$s&zrb_front_ut=%2$s",inspectId,AppSetting.curUser.zrb_front_ut);
  		CommonUtil.InfoLog("url", url);
     	
     	ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler()
    	{
 			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
 				mloadingView.HideText(User_my_surveyinfo.this.getString(R.string.error_net_loadfail)).ShowRefleshBtn(true).ShowError();
			}
 		   @Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
 			   
 				String results=new String(arg2);
				try 
				{
 			       Gson gson = new Gson();  
 			       ProjectSurveyDetailDtos tmpDto=	gson.fromJson(results, ProjectSurveyDetailDtos.class);
 			       msurveyProcessAdapter=new Project_surveyprocessAdapter(User_my_surveyinfo.this);
 			       if(tmpDto.res==1) {
 			    	   mloadingView.Hide();
   			    	   String tmplonlat= tmpDto.data.projectInfoVo.geoCoor;  //"geoCoor":"116.703687,23.36818"
 			    	   if(!TextUtils.isEmpty(tmplonlat)&&tmplonlat.contains(",")) {
 			    		  Lat=Double.parseDouble(tmplonlat.split(",")[1]);
 			    		  Lng=Double.parseDouble(tmplonlat.split(",")[0]); 
  			    	   }
 			    	   showstep(tmpDto.data.inspectStatus);
					   boolean isDone = tmpDto.data.inspectStatus == Constants.InspectCancel
								|| tmpDto.data.inspectStatus == Constants.InspectFinish;// ���
																						// ȡ��
   			    	   if(isDone){   
  			    		   cancelbtn.setVisibility(View.VISIBLE);
  			    		   cancelbtn.setText("����ԤԼ");
  			    	   }
  			    	   else if(tmpDto.data.inspectStatus==Constants.InspectConfirm){   //ȷ��
   			    		  cancelbtn.setText("�绰ȡ��ԤԼ");
  			    	   }
   			    	   
  			    	   tv_location_area.setText(tmpDto.data.projectName);
  			    	   projectId = tmpDto.data.projectId;
  			    	   curSurveyDto= tmpDto.data;
  			    	   
  			    	   if( tmpDto.data.inspectStatus == Constants.InspectCancel){
  			    		 Date dat=new Date(tmpDto.data.updateTime);
  			    		 SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  			    		 
  			    		 cancel_reason.setText("���� " + sf.format(dat) + " ȡ���˶�" + tmpDto.data.projectName + "��������룬��" + tmpDto.data.reasonTypeZH + "ԭ�򣬿����ѳɹ�ȡ��");
  			    	   }
  			    	   
   			           msurveyProcessAdapter.CurrentDatas.addAll(tmpDto.data.event);
  		               attachlistview.setAdapter(msurveyProcessAdapter);
 			      }
 			      else
  			    	 mloadingView.HideText("����"+tmpDto.msg).ShowRefleshBtn(true).ShowError();
     			}
				catch(Exception e){
					mloadingView.HideText(User_my_surveyinfo.this.getString(R.string.error_serverdata_loadfail))
					            .ShowRefleshBtn(true).ShowError();
					
 				}
  			}});
 	}
 
	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "����ȡ����...", true,
					true);
		else
			progTip.Show("����ȡ����...");
	}

	
	public void showCancelDialog()
	{
		DialogBuilder builder2 = new DialogBuilder(User_my_surveyinfo.this);
        //builder2.setTheme(Resource.Style.customDialog);
		builder2.setParentlayout(R.layout.custom_ucenter_dialog);
        builder2.setContentView(R.layout.u_center_org_auth); //ac_dialog_cancel; 
        builder2.setPositiveTitle("����");
    	TextView hitetxt= (TextView)builder2.getCurContentView().findViewById(R.id.tv_authstr);
    	String msource=this.getResources().getString(R.string.project_survey_phonecancel);
    	hitetxt.setText(msource);
            
        builder2.setCloseOnclick(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					AuthDialog.dismiss();
					if(arg0.getId()==R.id.btn_confirm){
 						   Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +Constants.serverPhone));
 						  User_my_surveyinfo.this.startActivity(intent);
					 }
					}
		         }); 
        AuthDialog = builder2.create();
        AuthDialog.show();
		
	}
	
	/**����״̬��0��ȡ��1�����룻2��ȷ�ϣ�3�����**/
   private void cancelSurvey(){
	   switch(curSurveyStatus){
	     case Constants.InspectApply:  //����---->ȡ��
	    	Intent surveyback = new Intent(this, User_my_surveyback.class);
			surveyback.putExtra("inspectId", inspectId);
			this.startActivityForResult(surveyback, 101);
			
		   break;
	     case Constants.InspectCancel://ȡ�����---->���¿���
	    	 surveyApply();
	    	 break;
	     case Constants.InspectFinish:
	    	 surveyApply();
	    	 break; 
	     case Constants.InspectConfirm://ȷ��----->�绰ȡ��
	    	 showCancelDialog();
	    	 break; 
	   }
	   
   }
   
   @Override
	protected void	onActivityResult(int requestCode, int resultCode, Intent data){
	    if(resultCode==RESULT_OK){
		  switch (requestCode) { // resultCodeΪ�ش��ı�ǣ�����B�лش�����RESULT_OK
		    case 101:
				mloadingView.ShowLoading();
				LoadData();
		    	break;
		   default:
			break;
		  }
	    }
	    super.onActivityResult(requestCode, resultCode, data);
  } 
  	
   
   private void test(){
	   View tmp=findViewById(R.id.cancel_layout);
	   tmp.setVisibility(View.VISIBLE);
	   View tmpproc=findViewById(R.id.process_layout);
	   tmpproc.setVisibility(View.INVISIBLE);
	   
	   
	   YoYo.with(Techniques.BounceInDown)
	   .duration(700)
	   .playOn(tmp);
   }
 
   
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.logout_btn:
			//test();
 			  cancelSurvey();
			break;
     	case R.id.tv_location_layout:
     		Intent intent = new Intent(this, Project_info_lience.class);
			intent.putExtra("projectId",curSurveyDto.projectId);
			intent.putExtra("title", curSurveyDto.projectName);
			startActivity(intent);
     		break;
    	case R.id.btn_reflesh:
    		mloadingView.HideText("Ŭ��������...").ShowLoading();
    		LoadData() ;
      		break;
    	case R.id.relative_afk:
    		 if(Lng!=0&&Lat!=0){
    			 
     			 Intent it = new Intent(this, BaiduMapActivity.class);
     		 	 it.putExtra("latitude", Lat);
     		 	 it.putExtra("longitude", Lng);
     		 	 it.putExtra("address", "");
     		 	 startActivity(it);
    		  } 
    		break;
    	case R.id.relative_afk1:
    		showAuthentication();
      		break;
    	case R.id.relative_afk2:
    		Intent comment = new Intent(this, Project_commentActivity.class);
    		comment.putExtra("projectId", projectId);
			startActivity(comment);
      		break; 
 
 		}
 	}
 
	public void showAuthentication()
	{
		DialogBuilder builder2 = new DialogBuilder(User_my_surveyinfo.this);
        //builder2.setTheme(Resource.Style.customDialog);
		builder2.setParentlayout(R.layout.custom_ucenter_dialog);
        builder2.setContentView(R.layout.u_center_org_auth); //ac_dialog_cancel; 
        builder2.setPositiveTitle("����");
    	TextView hitetxt= (TextView)builder2.getCurContentView().findViewById(R.id.tv_authstr);
    	String msource=this.getResources().getString(R.string.user_center_profile_edit_org_authtrue1);
    	hitetxt.setText(msource);
            
        builder2.setCloseOnclick(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					AuthDialog.dismiss();
					if(arg0.getId()==R.id.btn_confirm){
 						   Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +Constants.serverPhone));//"400-688-0101"
 						  User_my_surveyinfo.this.startActivity(intent);
					 }
					}
		         }); 
        AuthDialog = builder2.create();
        AuthDialog.show();
		
	}
	private void surveyApply(){
		   
		   if(AppSetting.curUser!=null){
				/*if(AppSetting.curUser.userType.equals("2")) //gov
				{	
	 				CommonUtil.showToast("��ǰ����ǹ���Ա�����ܽ��п���", User_my_surveyinfo.this);
				   return;
				}*/
			}
		   if(AppSetting.curUser==null){
				 Intent it = new Intent(this, User_phone_login.class);
				 it.putExtra("forResult", true);
				 this.startActivityForResult(it, 101);
			    return;
			}
			else{
		      Intent it2 = new Intent(User_my_surveyinfo.this, Project_surveyActivity.class);
		      it2.putExtra("projectId", projectId);
		      startActivity(it2);
		    }
	   }

}
